# This file is part of Sonedyan.
#
# Sonedyan is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation;
# either version 3 of the License, or (at your option) any
# later version.
#
# Sonedyan is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public
# License along with Octave; see the file COPYING.  If not
# see <http://www.gnu.org/licenses/>.
#
# Copyright (C) 2009-2012 Jimmy Dubuisson <jimmy.dubuisson@gmail.com>

source('cycles.R')
source('metrics.R')

print.stats <- function(name, stats)
{
	print(paste(name, " #v:", stats[["nv"]]))
	print(paste(name, " #e:", stats[["ne"]]))
	print(paste(name, " density:", stats[["dens"]]))
	print(paste(name, " CPL:", stats[["cpl"]]))
	print(paste(name, " diameter (d):", stats[["ddiam"]]))
	print(paste(name, " diameter (u):", stats[["udiam"]]))
	print(paste(name, " avg deg:", stats[["avgdeg"]]))
	print(paste(name, " avg pr:", stats[["avgpr"]]))
	print(paste(name, " transitivity:", stats[["gtrans"]]))
}

get.3cycles.vids <- function(g)
{
	adj <- get.adjacency(g)
	pow <- adj %*% adj %*% adj
	which(diag(pow) != 0)
}

remove.shortcuts <- function(g, ec3names)
{
	ec3ids <- c()

	for (i in c(1:length(ec3)))
	{
        	evnames <- strsplit(ec3[i], "\\|")[[1]]
        	vid1 <- which(V(seed)$id == evnames[1])
        	vid2 <- which(V(seed)$id == evnames[2])
        	eid <- E(seed)[vid1 %->% vid2]
        	ec3ids <- append(ec3ids, eid)
	}

	enc3ids <- setdiff(E(g), ec3ids)
	delete.edges(g, enc3ids)
}

get.reduced.clique.words <- function(seed32.core, mcliques)
{
	nc <- length(mcliques)
	
	loginfo("Computing list of clique words...")
	
	cliques <- list()

	pb <- txtProgressBar(title = "List of words computing", min = 1, max = nc, style = 3)
	counter <- 1

	for (i in c(1:nc))
	{
		nodes <- V(seed32.core)[mcliques[[i]]]$name
		words <- c()

		for (j in c(1:length(nodes)))
		{
			node <- nodes[[j]]

			for (z in strsplit(node, "\\."))
			{
				words <- append(words, z)
			}
		}

		words <- tolower(unique(words))
		cliques[[i]] <- words
		
		# update progress bar
		setTxtProgressBar(pb, counter)
		counter <- counter + 1
	}

	close(pb)
	
	loginfo("Sorting list of clique words by size...")

	# cliques sorted by size
	scliques <- list()

	cl <- lapply(cliques, length)
	minl <- min(unlist(cl))
	maxl <- max(unlist(cl))

	for (p in c(minl:maxl))
	{
		ids <- which(cl == p)
		scliques <- append(scliques, cliques[ids])
	}
	
	loginfo("Reducing list of clique words...")
	
	# reduced list of words
	rcliques <- list()
	counter <- 1

	for (i in c(1:(nc-1)))
	{
		is.subset <- FALSE

		for (j in c((i+1):nc))
		{
			ci <- scliques[[i]]
			cj <- scliques[[j]]

			if (!(any(ci %in% cj == FALSE)))
			{
				is.subset <- TRUE
				break
			}
		}
	
		if (!is.subset)
		{
			rcliques[[counter]] <- scliques[[i]]
			counter <- counter + 1
		}
	}

	rcliques
}

#core <- read.graph(file = "eat-core-graphml.xml", format = "graphml")
#fa.core <- read.graph(file = "fa-core-graphml.xml", format = "graphml")

#print(paste("# vertices: ", length(V(core))))
#print(paste("# edges: ", length(E(core))))

# EAT contains self loops
#core <- simplify(core)

# cpl: characteristic path length
# msccs: main SCC size
# mwccs: main WCC size
# ddiam: directed diameter
# udiam: undirected diameter
# eff: efficiency
# assort: assortativity
# gtrans: global transitivity (global CC)
# altrans: avg of local transitivities (avg of local CCs)
# dens: density
# nv: # vertices
# ne: # edges
# avgpr: avg pagerank
# avgdeg: avg degree
# avgindeg
# avgoutdeg
# maxdeg
# maxindeg
# maxoutdeg
# mindeg
# minindeg
# minoutdeg 
#metrics <- c("cpl", "ddiam", "udiam", "dens", "nv", "ne", "avgdeg", "avgpr", "gtrans")

#stats <- get.graph.stats(core, metrics)
#print.stats("Core", stats)

#cvids <- get.3cycles.vids(core)
#print(paste("# 3-cycles vertices: ", length(cvids)))

#inter.core <- intersect(tolower(V(core)$id), tolower(V(fa.core)$id))
#print(inter.core)
#print(paste("# FA-Core inter EAT-Core: ", length(inter.core)))

### seed ###

#seed <- induced.subgraph(core, cvids)
#write.graph(seed, file= "eat-seed-graphml.xml", format = "graphml")

#seed <- read.graph(file = "eat-seed-graphml.xml", format = "graphml")
#fa.seed <- read.graph(file = "fa-seed-graphml.xml", format = "graphml")

#seedc <- clusters(seed, mode = "strong")
#print(paste("Seed # SCCs:", seedc$no))
#print(paste("Seed main SCC size:", max(seedc$csize)))

#stats3b <- get.graph.stats(seed, metrics)
#print.stats("Seed", stats3b)

#inter.seed <- intersect(tolower(V(seed)$id), tolower(V(fa.seed)$id))
#print(inter.seed)
#print(paste("# FA-Seed inter EAT-Seed: ", length(inter.seed)))

# logging config
basicConfig()
#setLevel('ERROR')

#c3 <- get.cycles(seed,3)
#saveRDS(c3, "eat-seed-3cycles.rds")
#c3 <- readRDS("eat-seed-3cycles.rds")

#ec3ids <- get.3cycles.vids.2(seed)
#saveRDS(ec3ids, "eat-seed-ec3ids.rds")
#ec3ids <- readRDS("eat-seed-ec3ids.rds")
#seed.cleaned <- remove.shortcuts(seed, c3$e)

#enc3ids <- setdiff(E(seed), ec3ids)
#seed.cleaned <- delete.edges(seed, enc3ids)
#write.graph(seed.cleaned, file= "eat-seed3-graphml.xml", format = "graphml")
#seed3 <- read.graph(file = "eat-seed3-graphml.xml", format = "graphml")

#seed32 <- get.3cycles.subgraph.reduction(c3$cn)
#write.graph(seed32, file= "eat-seed32-graphml.xml", format = "graphml")
#seed32 <- read.graph(file = "eat-seed32-graphml.xml", format = "graphml")

#s32cs <- clusters(seed32, mode = "weak")
#print(paste("Seed32 # SCCs:", s32cs$no))
#print(paste("Seed32 main WCC size:", max(s32cs$csize)))
#print(paste("Seed32 # WCC size 1:", length(which(s32cs$csize == 1))))

#seed32.core <- get.main.cc(seed32, mode = "weak")
#write.graph(seed32.core, file= "eat-seed32-core-graphml.xml", format = "graphml") 
seed32.core <- read.graph(file = "eat-seed32-core-graphml.xml", format = "graphml")

#print(length(V(seed32.core)))
#print(length(E(seed32.core)))

#mcliques <- maximal.cliques(seed32.core)
#saveRDS(mcliques, "maximal-cliques.rds")
mcliques <- readRDS("maximal-cliques.rds")

print(length(mcliques))

words <- get.reduced.clique.words(seed32.core, mcliques)

saveRDS(words, "words.rds")

# get cliques size
rcl <- lapply(words, length)

for (i in c(min(unlist(rcl)):max(unlist(rcl))))
{
	lx <- length(which(rcl == i))
	print(paste("#", i, ":", lx))
}

### shell ###

#shell <- delete.vertices(core, cvids)
#write.graph(shell, file= "eat-shell-graphml.xml", format = "graphml")

#shellc <- clusters(shell, mode = "strong")
#print(paste("Shell # SCCs:", shellc$no))
#print(paste("Shell main SCC size:", max(shellc$csize)))

#stats4b <- get.graph.stats(shell, metrics)
#print.stats("Shell", stats4b)

### equivalent ER ###

# Core-ER

#core.er <- erdos.renyi.game(7754, 247172, type = "gnm", directed = TRUE)
#V(core.er)$id <- paste(c(1:length(V(faer))), sep = "")
#E(core.er)$id <- paste(c(1:length(E(faer))), sep = "")

#stats.core.er <- get.graph.stats(core.er, metrics)
#print.stats("FA-ER", stats.core.er)

# Seed-ER

#seeder <- erdos.renyi.game(7500, 238677, type = "gnm", directed = TRUE)
#V(seeder)$id <- paste(c(1:length(V(seeder))), sep = "")
#E(seeder)$id <- paste(c(1:length(E(seeder))), sep = "")

#stats.seeder <- get.graph.stats(seeder, metrics)
#print.stats("Seed-ER", stats.seeder)

